package com.example.chatroom.controller;

import com.example.chatroom.common.component.OnlineUserManager;
import com.example.chatroom.common.errorcode.ServiceErrorCodeConstants;
import com.example.chatroom.common.exception.ServiceException;
import com.example.chatroom.common.utils.JacksonUtil;
import com.example.chatroom.controller.param.WebSocketApplyFriendParam;
import com.example.chatroom.controller.param.WebSocketMessageParam;
import com.example.chatroom.controller.result.WebSocketApplyFriendResult;
import com.example.chatroom.dao.dataobject.ApplyFriendDO;
import com.example.chatroom.dao.dataobject.MessageDO;
import com.example.chatroom.dao.dataobject.MessageSessionDO;
import com.example.chatroom.dao.dataobject.MessageSessionUserDO;
import com.example.chatroom.dao.mapper.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.ParameterResolutionDelegate;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.Date;
import java.util.concurrent.ConcurrentHashMap;

@Component
@Slf4j
public class WebSocketApplyFriend extends TextWebSocketHandler {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ApplyFriendMapper applyFriendMapper;
    @Autowired
    private MessageSessionMapper messageSessionMapper;
    @Autowired
    private MessageMapper messageMapper;
    @Autowired
    private MessageSessionUserMapper messageSessionUserMapper;

    //使用map记录userId与websocketSession映射关系
    private ConcurrentHashMap<Long,WebSocketSession>map=new ConcurrentHashMap<>();

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        log.info("WebSocketApplyFriend 服务端连接成功");
        Long userId = (Long)session.getAttributes().get("userId");
        if(userId==null){
            log.info("Httpsession userId:{}", userId);
            return;
        }
        map.put(userId,session);
    }


    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        log.info("WebSocketApplyFriend 服务端收到消息 message:{}",message.toString());
        //1-    获取当前登陆用户Id（发送信息者）
        Long userId = (Long)session.getAttributes().get("userId");
        if(userId==null){
            log.info("Httpsession userId:{}", userId);
            return;
        }

        //2-    将负载信息转换为对象
        WebSocketApplyFriendParam webSocketApplyFriendParam = JacksonUtil.readValue(message.getPayload(), WebSocketApplyFriendParam.class);
        log.info("message:"+JacksonUtil.writeValueAsString(webSocketApplyFriendParam));

        if(webSocketApplyFriendParam.getType().equals("applyFriend")){
            transferApplyFriend(webSocketApplyFriendParam);
        }else if(webSocketApplyFriendParam.getType().equals("agreeButton")){
            agreeFunction(userId,webSocketApplyFriendParam);
        }else if(webSocketApplyFriendParam.getType().equals("rejectButton")){
            rejectFunction(webSocketApplyFriendParam);
        }
        else{
            log.info("message type:{}",webSocketApplyFriendParam.getType());
            return;
        }

    }

    private void rejectFunction(WebSocketApplyFriendParam webSocketApplyFriendParam) {
    }

    private void agreeFunction(Long userId,WebSocketApplyFriendParam webSocketApplyFriendParam) throws IOException {
        ApplyFriendDO applyFriendDO = applyFriendMapper.selectById(webSocketApplyFriendParam.getId());
        //1-    往会话表增加一条记录
        MessageSessionDO messageSessionDO=new MessageSessionDO();
        messageSessionDO.setDeleteFlag((byte) 0);
        messageSessionDO.setGmtCreate(new Date());
        messageSessionDO.setGmtModified(new Date());
        messageSessionMapper.insertSelective(messageSessionDO);
        //2-    会话用户表增加一条记录
        MessageSessionUserDO messageSessionUserDO=new MessageSessionUserDO();
        messageSessionUserDO.setSessionId(messageSessionDO.getId());
        messageSessionUserDO.setUserId(applyFriendDO.getToId());
        messageSessionUserMapper.insertSelective(messageSessionUserDO);

        MessageSessionUserDO messageSessionUserDO1=new MessageSessionUserDO();
        messageSessionUserDO1.setSessionId(messageSessionDO.getId());
        messageSessionUserDO1.setUserId(applyFriendDO.getFormId());
        messageSessionUserMapper.insertSelective(messageSessionUserDO1);
        //3-    信息表中增加一条记录
        MessageDO messageDO=new MessageDO();
        //被添加者给添加者发送 ”我们已经是好友了，开始对话吧“
        messageDO.setFormId(applyFriendDO.getToId());
        messageDO.setSessionId(messageSessionDO.getId());
        messageDO.setContent("我们已经是好友了，开始对话吧!");
        messageMapper.insertSelective(messageDO);
        //4-    构造负载信息
        WebSocketApplyFriendResult webSocketApplyFriendResult=new WebSocketApplyFriendResult();
        webSocketApplyFriendResult.setType("agreeButton");
        webSocketApplyFriendResult.setPostTime(applyFriendDO.getGmtCreate());
        webSocketApplyFriendResult.setApplyContent(applyFriendDO.getApplyContent());
        webSocketApplyFriendResult.setId(webSocketApplyFriendParam.getId());

        //5-    发送信息 如果当前登陆者是甲那么就发给乙
        WebSocketSession webSocketSession = map.get(applyFriendDO.getToId());
        //被添加者的姓名
        webSocketApplyFriendResult.setFormName(userMapper.selectByPrimaryKey(applyFriendDO.getFormId()).getUserName());
        String str1 = JacksonUtil.writeValueAsString(webSocketApplyFriendResult);
        webSocketSession.sendMessage(new TextMessage(str1));

        WebSocketSession webSocketSession1 = map.get(applyFriendDO.getFormId());
        //被添加者的姓名
        webSocketApplyFriendResult.setFormName(userMapper.selectByPrimaryKey(applyFriendDO.getToId()).getUserName());
        String str2 = JacksonUtil.writeValueAsString(webSocketApplyFriendResult);
        webSocketSession1.sendMessage(new TextMessage(str2));
    }

    private void transferApplyFriend(WebSocketApplyFriendParam webSocketApplyFriendParam) throws IOException {
        //1-    获取信息记录
        ApplyFriendDO applyFriendDO = applyFriendMapper.selectById(webSocketApplyFriendParam.getId());
        log.info("applyFriendDO:{}",JacksonUtil.writeValueAsString(applyFriendDO));
        //2-    获取session
        WebSocketSession webSocketSession = map.get(applyFriendDO.getToId());
        //3-    构造负载信息
        WebSocketApplyFriendResult webSocketApplyFriendResult=new WebSocketApplyFriendResult();
        webSocketApplyFriendResult.setType("applyFriend");
        webSocketApplyFriendResult.setFormName(userMapper.selectByPrimaryKey(applyFriendDO.getFormId()).getUserName());
        webSocketApplyFriendResult.setPostTime(applyFriendDO.getGmtCreate());
        webSocketApplyFriendResult.setApplyContent(applyFriendDO.getApplyContent());
        webSocketApplyFriendResult.setId(applyFriendDO.getId());
        String str = JacksonUtil.writeValueAsString(webSocketApplyFriendResult);
        webSocketSession.sendMessage(new TextMessage(str));
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        log.info("WebSocketApplyFriend 服务端连接异常 exception:{}",exception);
        Long userId = (Long)session.getAttributes().get("userId");
        if(userId==null){
            log.info("Httpsession userId:{}", userId);
            return;
        }
        map.remove(userId,session);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        log.info("WebSocketApplyFriend  服务端断开连接 status:{}",status);
        Long userId = (Long)session.getAttributes().get("userId");
        if(userId==null){
            log.info("Httpsession userId:{}", userId);
            return;
        }
        map.remove(userId,session);
    }
}
